/*
 * @Date: 2021-06-30 20:36:39
 * @LastEditors: wangjun haodreams@163.com
 * @LastEditTime: 2024-11-06 16:31:08
 * @FilePath: \libs\config\jsonconf\conf.go
 * @Description:
 */
package jsonconf

import (
	"encoding/json"
	"errors"
	"os"
	"sort"

	"gitee.com/haodreams/libs/config"
)

// Conf .
type Conf struct {
	path string
	config.Conf
}

// NewConf .
func NewConf() *Conf {
	c := new(Conf)
	c.SetDriverName("json")
	return c
}

// Load 加载配置来自文件
func Load(file string) (conf config.Configer, err error) {
	c := new(Conf)
	conf, err = c.Load(file)

	return
}

// Load 读取配置
func (m *Conf) Load(file interface{}) (conf config.Configer, err error) {
	path, ok := file.(string)
	if !ok {
		return nil, errors.New("invalid paramter")
	}
	conf = m
	m.path = path
	data, err := os.ReadFile(path)
	if err != nil {
		return
	}
	err = m.LoadData(data)
	return
}

// LoadData .
func (m *Conf) LoadData(data []byte) (err error) {
	var kvs []*config.KV
	err = json.Unmarshal(data, &kvs)
	if err != nil {
		return
	}
	for i, kv := range kvs {
		kv.OrderNo = i + 1
	}
	m.SetList(kvs)
	return
}

// Save 保存配置
func (m *Conf) Save(file ...interface{}) (err error) {
	path := m.path
	var ok bool
	if len(file) > 0 {
		if path, ok = file[0].(string); !ok {
			return errors.New("invalid paramter")
		}
	}
	m.Lock()
	defer m.Unlock()

	list := m.List()
	sort.Slice(list, func(i, j int) bool {
		return list[i].Name < list[j].Name
	})

	data, err := json.MarshalIndent(list, "", " ")
	if err != nil {
		return
	}
	err = os.WriteFile(path, data, 0644)
	return
}
